package com.dura.strategy.filter.impl;

import com.dura.common.constant.CacheConstant;
import com.dura.common.enums.ExceptionEnums;
import com.dura.common.exception.StrategyException;
import com.dura.common.model.StandardSubmit;
import com.dura.strategy.util.ClientBalanceUtil;
import com.dura.strategy.client.BeaconCacheClient;
import com.dura.strategy.filter.StrategyFilter;
import com.dura.strategy.util.ErrorSendMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @version 1.0
 * @Author 振鹏
 * @Date 2025/3/18 8:43
 * @注释
 */
@Service(value = "fee")
@Slf4j
public class FeeStrategyFilter implements StrategyFilter {

    private final String BALANCE="balance";

    @Autowired
    private BeaconCacheClient cacheClient;

    @Autowired
    private ErrorSendMsgUtil errorSendMsgUtil;

    @Override
    public void strategy(StandardSubmit submit) {
        log.info("【策略模块-费用校验】 校验ing................");
        // 扣费操作 基于redis的费用扣除，redis原子性，保证不会出现并发问题。
        Long fee = submit.getFee();
        Long clientId = submit.getClientId();

        // 调用redis 扣减具体金额
        Long amount =cacheClient.hIncrBy(CacheConstant.CLIENT_BALANCE+clientId, BALANCE, -fee);

        // 当前客户的欠费金额的最大限制
        Long amountLimit =ClientBalanceUtil.getClientAmountLimit(submit.getClientId());

        // 判断是否超出，超过了就其他处理
        if(amount<amountLimit){
            log.info("【策略模块-扣费校验】   扣除费用后，超过欠费余额的限制，无法发送短信！");
            // 发送失败原因
            cacheClient.hIncrBy(CacheConstant.CLIENT_BALANCE+clientId,BALANCE,fee);
            submit.setErrorMsg(ExceptionEnums.BALANCE_NOT_ENOUGH.getMsg());
            // 将消息发送给消息队列，分别为 系统日志和用户推送
            errorSendMsgUtil.sendWriteLog(submit);
            errorSendMsgUtil.sendPushReport(submit);

            throw new StrategyException(ExceptionEnums.BALANCE_NOT_ENOUGH);
        }
        log.info("【策略模块-扣费校验】   扣除费用后，没有超过欠费余额的限制，可以发送短信！");
    }
}
